//
//  PQIAPManager.m
//  chuyong
//
//  Created by tikeios_002 on 2023/10/10.
//

#import "PQIAPManager.h"
#import "NSString+Base64.h"
#import "YBNetworking.h"
@interface PQIAPManager()

// 交易是否结束
@property (nonatomic, assign) BOOL isRequestFinished;
// 判断是购买还是恢复
@property (nonatomic, assign) BOOL isRestore;
@property (nonatomic,strong) SKProductsRequest *request;

@property (nonatomic,strong) SKPaymentTransaction * fishTran;
//订单号
@property (nonatomic, copy) NSString * saveOrderID;
//订单号
@property (nonatomic, assign) int buyType;

@property (nonatomic,copy) buyProductCompleteResponseSuccessBlock buySuccessBlock;
@property (nonatomic,copy) buyProductCompleteResponseFailuerBlock buyFailuerBlock;
@property (nonatomic,copy) buyProductCompleteResponseCheckFailuerBlock checkFailuerBlock;
@end

@implementation PQIAPManager

// 单例
+ (instancetype)sharedManager{
    static dispatch_once_t pred;
    static PQIAPManager *manager = nil;
    dispatch_once(&pred, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

// 创建时就开始监听购买事件
- (instancetype)init{
    
    if (self = [super init]) {
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        NSDictionary * dic = [[NSUserDefaults standardUserDefaults] objectForKey:USER_BUY_UPLOD_KEY];
        if(dic == nil || [dic isKindOfClass:[NSNull class]] || dic.count == 0){
//            if([[self getAppleOrderId] length] > 0){
//
//            }else{
                self.isRequestFinished = YES;
//            }
        }else{
            KWeakSelf
            NSString * urlstr = dic[@"url"];
            NSMutableDictionary * datas = [[NSMutableDictionary alloc]initWithDictionary:dic];
            NSString *receipt = [self getNowReceipt];
            [datas setObject:receipt forKey:@"receipt-data"];
            [datas removeObjectForKey:@"url"];
            [YBNetBase requestNotUrl:urlstr sendDic:datas successBlock:^(NSDictionary * _Nonnull data, NSInteger code, NSString * _Nonnull msg) {
                if(code == 200){
                    weakSelf.isRequestFinished = YES;
                    [[NSUserDefaults standardUserDefaults] removeObjectForKey:USER_BUY_UPLOD_KEY];
                }
            }];
        }
        
    }
    return self;
}
/**请求商品列表*/
- (void)requestProductWithId:(NSString *)productId orderId:(NSString *)orderId type:(int)type buySuccess:(buyProductCompleteResponseSuccessBlock)buySuccess buyFailuer:(buyProductCompleteResponseFailuerBlock)buyFailuer checkFailuer:(buyProductCompleteResponseCheckFailuerBlock)checkFailuer {
    self.buySuccessBlock = buySuccess;
    self.buyFailuerBlock = buyFailuer;
    self.checkFailuerBlock = checkFailuer;
    self.buyType = type;
    self.isRestore = NO;
    if (self.isRequestFinished) {
        if ([SKPaymentQueue canMakePayments]) { //用户允许app内购
            if (productId.length) {
                self.isRequestFinished = NO; //正在请求
                self.saveOrderID = orderId;
                NSLog(@"%@商品正在请求中...",productId);
                NSSet *product = [[NSSet alloc] initWithArray:@[productId]];
                _request = [[SKProductsRequest alloc] initWithProductIdentifiers:product];
                _request.delegate = self;
                [_request start];
            }
        } else { //没有权限
            self.isRequestFinished = YES; //完成请求
            NSLog(@"没有购买权限");
            [SVProgressHUDTool showErrorWithStatus:@"没有购买权限"];
            if(self.buyFailuerBlock){
                self.buyFailuerBlock();
            }
        }
    } else {
        NSDictionary * dic = [[NSUserDefaults standardUserDefaults] objectForKey:USER_BUY_UPLOD_KEY];
        if(dic == nil || [dic isKindOfClass:[NSNull class]] || dic.count == 0){
            [SVProgressHUDTool showErrorWithStatus:@"上次请求购买未完成，请稍后重试！"];
            if(self.buyFailuerBlock){
                self.buyFailuerBlock();
            }
        }else{
            KWeakSelf
            NSString * urlstr = dic[@"url"];
            NSMutableDictionary * datas = [[NSMutableDictionary alloc]initWithDictionary:dic];
            NSString *receipt = [self getNowReceipt];
            [datas setObject:receipt forKey:@"receipt-data"];
            [datas removeObjectForKey:@"url"];
            [YBNetBase requestNotUrl:urlstr sendDic:datas successBlock:^(NSDictionary * _Nonnull data, NSInteger code, NSString * _Nonnull msg) {
                if(code == 200){
                    weakSelf.isRequestFinished = YES;
                    [[NSUserDefaults standardUserDefaults] removeObjectForKey:USER_BUY_UPLOD_KEY];
                }
            }];
        }
    }
}
// 请求购买商品列表的第一个
#pragma mark SKProductsRequestDelegate 请求商品列表后的回调
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    NSArray *product = response.products;
    if (product.count == 0){
        [SVProgressHUDTool showErrorWithStatus:@"购买商品错误"];
        if(self.buyFailuerBlock){
            self.buyFailuerBlock();
        }
        self.isRequestFinished = YES; //完成请求
        return;
    } else {
        if (response.invalidProductIdentifiers.count) {
            NSLog(@"商品请求错误,error:%@", response.invalidProductIdentifiers);
            [SVProgressHUDTool showErrorWithStatus:@"购买商品错误"];
            if(self.buyFailuerBlock){
                self.buyFailuerBlock();
            }
            self.isRequestFinished = YES; //完成请求
            return;
        }
        NSLog(@"商品详情:%@",[product[0] description]);
        NSLog(@"商品价格:%@",[product[0] price]);
        NSLog(@"商品名字:%@",[product[0] productIdentifier]);
        SKProduct *product = response.products[0];
        SKMutablePayment *payment = [[SKMutablePayment alloc] init];
        if(self.saveOrderID.length != 0){
            payment.applicationUsername = self.saveOrderID;
        }
        payment.productIdentifier = product.productIdentifier;
        // 请求购买
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
}
// 处理请求购买后的回调
#pragma mark - SKProductsRequestDelegate 请求购买后的回调
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
    if (!self.isRestore) {
        KWeakSelf
        for (SKPaymentTransaction *tran in transactions) {

            switch (tran.transactionState) {
                case SKPaymentTransactionStatePurchasing: // 正在交易
                    break;
                case SKPaymentTransactionStatePurchased: // 交易完成
                    weakSelf.fishTran = tran;
                    if([tran.payment.applicationUsername length] > 0){
                        weakSelf.saveOrderID = tran.payment.applicationUsername;
                    }
                    if (tran.originalTransaction) {
                      // 如果是自动续费的订单,originalTransaction会有内容
                      if (tran.originalTransaction.transactionIdentifier) {
                        NSLog(@"自动续费的订单ID = %@",tran.originalTransaction.transactionIdentifier);
                        [weakSelf saveOrderId:tran.originalTransaction.transactionIdentifier];
                      }
                    } else {
                        // 普通购买，以及第一次购买自动订阅
                        if (tran.transactionIdentifier) {
                            [weakSelf saveOrderId:tran.transactionIdentifier];
                        }
                    }
                    [weakSelf vertifyReceipt:0]; // 校验购买凭证
                    break;
                
                case SKPaymentTransactionStateFailed: // 交易失败
                    if (tran.error.code == SKErrorPaymentCancelled) {
                        [SVProgressHUDTool showErrorWithStatus:@"用户取消购买"];
                        if(weakSelf.buyFailuerBlock){
                            weakSelf.buyFailuerBlock();
                        }
                        [weakSelf completeTransaction:tran];
                    }else{
                        weakSelf.fishTran = tran;
                        if([tran.payment.applicationUsername length] > 0){
                            weakSelf.saveOrderID = tran.payment.applicationUsername;
                        }
                        if (tran.originalTransaction) {
                          // 如果是自动续费的订单,originalTransaction会有内容
                          if (tran.originalTransaction.transactionIdentifier) {
                            NSLog(@"自动续费的订单ID = %@",tran.originalTransaction.transactionIdentifier);
                            [weakSelf saveOrderId:tran.originalTransaction.transactionIdentifier];
                          }
                        } else {
                            // 普通购买，以及第一次购买自动订阅
                            if (tran.transactionIdentifier) {
                                [weakSelf saveOrderId:tran.transactionIdentifier];
                            }
                        }
                        [weakSelf vertifyReceipt:1];
                    }
                    break;
                
                case SKPaymentTransactionStateRestored: // 已经购买过该商品
                    weakSelf.fishTran = tran;
                    if([tran.payment.applicationUsername length] > 0){
                        weakSelf.saveOrderID = tran.payment.applicationUsername;
                    }
                    if (tran.originalTransaction) {
                      // 如果是自动续费的订单,originalTransaction会有内容
                      if (tran.originalTransaction.transactionIdentifier) {
                        NSLog(@"自动续费的订单ID = %@",tran.originalTransaction.transactionIdentifier);
                        [weakSelf saveOrderId:tran.originalTransaction.transactionIdentifier];
                      }
                    } else {
                        // 普通购买，以及第一次购买自动订阅
                        if (tran.transactionIdentifier) {
                            [weakSelf saveOrderId:tran.transactionIdentifier];
                        }
                    }
                    [weakSelf vertifyReceipt:2];
                    break;
                default:
                    break;
            }
        }
    }
}
// 根据公司需求校验凭证0成功1失败2已经购买
- (void)vertifyReceipt:(NSInteger)buytype{
    NSURL * receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    if ([[NSFileManager defaultManager] fileExistsAtPath:[receiptURL path]] || buytype > 0){
        KWeakSelf
        [self vertifyReceipt:buytype success:^{
            if(weakSelf.buySuccessBlock){
                weakSelf.buySuccessBlock();
            }
            [weakSelf completeTransaction:weakSelf.fishTran];
            [weakSelf removeOrderId];
        }successFail:^(NSString *str) {
            if(weakSelf.checkFailuerBlock){
                weakSelf.checkFailuerBlock(str);
            }else{
                [SVProgressHUDTool showErrorWithStatus:@"购买失败,请稍后再试"];
            }
            [weakSelf completeTransaction:weakSelf.fishTran];
            [weakSelf removeOrderId];
        } failure:^(NSError * err) {
            [SVProgressHUDTool dismiss];
            [YBMsgPop showPop:NSLocalizedString(@"连接失败，请检查网络", nil)];
            if(weakSelf.buyFailuerBlock){
                weakSelf.buyFailuerBlock();
            }
        }];
    } else {
        // 如果凭证为空，则再发一次凭证请求
        SKReceiptRefreshRequest *refreshReceiptRequest = [[SKReceiptRefreshRequest alloc] initWithReceiptProperties:@{}];
        refreshReceiptRequest.delegate = self;
        [refreshReceiptRequest start];
    }
}
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    self.isRequestFinished = YES; // 请求完成
    if(transaction){
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    }
}
// 校验凭证
- (void)vertifyReceipt:(NSInteger)buytype success:(void(^)(void))success successFail:(void(^)(NSString * str))successFail failure:(void (^)(NSError *))failure {
    NSString *receipt = [self getNowReceipt];
    KMutableDic(sendDic)
    KWeakSelf
    sendDic[@"receipt-data"] = receipt;
    
    if([[self getOrderId] length] != 0){
        sendDic[@"order_no"] = [self getOrderId];
    }
    if(buytype == 1){
        sendDic[@"state"] = @"2";
    }else if(buytype == 2){
        sendDic[@"state"] = @"3";
    }
    NSString * path = @"";
    if(self.buyType == 0){
        path = @"buyApple";
    }else if (self.buyType == 1){
        
    }else if (self.buyType == 2){
        path = @"buyTranslateCoin";
    }
   
    
    [YBNetBase memberAccountBuyAppleRequest:sendDic url:path successBlock:^(NSDictionary * _Nonnull data, NSInteger code, NSString * _Nonnull msg) {
        if(code == 200){
            if(success){
                success();
            }
        }else if(code == 122 || receipt.length == 0 || buytype > 0){
            //失败校验
            if(buytype == 1){
                [SVProgressHUDTool showErrorWithStatus:@"购买失败.请稍后再试"];
            }else if (buytype == 2){
                [SVProgressHUDTool showErrorWithStatus:@"已经购买过该商品！"];
            }
            if(weakSelf.buyFailuerBlock){
                weakSelf.buyFailuerBlock();
            }
            [weakSelf completeTransaction:weakSelf.fishTran];
            [weakSelf removeOrderId];
        }else{
            if(successFail){
                successFail(msg);
            }
        }
    }];
}

// 获取凭证
- (NSString *)getNowReceipt {
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
    if(receiptData.length == 0){
        return @"";
    }else{
        NSString *encodeReceiptStr = [NSString base64StringFromData:receiptData length:[receiptData length]];
        return encodeReceiptStr;
    }
}

// 保存订单ID
- (void)saveOrderId:(NSString *)orderId{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:orderId forKey:@"appleOrderId"];
    [defaults setValue:self.saveOrderID forKey:@"orderId"];
    [defaults synchronize];
}
// 删除订单ID
- (void)removeOrderId{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:@"appleOrderId"];
    [defaults removeObjectForKey:@"orderId"];
    [defaults synchronize];
}
// 获取订单ID
- (NSString *)getAppleOrderId{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return [defaults valueForKey:@"appleOrderId"];
}
// 获取订单ID
- (NSString *)getOrderId{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if([[defaults valueForKey:@"orderId"] isKindOfClass:[NSNull class]] || [[defaults valueForKey:@"orderId"] length] == 0){
        return @"";
    }else{
        return [defaults valueForKey:@"orderId"];
    }
    
}
// 销毁时就移除监听事件
- (void)dealloc{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

- (void)restoreBuy {
    // 如果凭证为空，则再发一次凭证请求
//    SKReceiptRefreshRequest *refreshReceiptRequest = [[SKReceiptRefreshRequest alloc] initWithReceiptProperties:@{}];
//    refreshReceiptRequest.delegate = self;
//    [refreshReceiptRequest start];
    self.isRequestFinished = YES;
}

@end
